package com.itheima.annotion;

import com.alibaba.fastjson.JSON;
import com.itheima.wechat.JedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletRequest;

/*配置Member注解*/
public class MemberArgumentResolver implements HandlerMethodArgumentResolver {


    @Autowired
    JedisPool jedisPool;
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        /*指定要设置的注解*/
        return methodParameter.hasParameterAnnotation(Member.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        /*从request中获取 token 的值*/
        String token = request.getHeader("token");
        /*登录校验，根据键取出json字符串*/
        String item = jedisPool.getResource().get(token);
        /*将json字符串转化为对象*/
        return JSON.parseObject(item, com.itheima.pojo.Member.class);
    }
}
